const express = require('express')
//创建web服务器实例对象
const app = express()

//导入并配置cors中间件解决跨域问题
const cors = require('cors')
app.use(cors())

//配置解析表单数据的中间件，只能解析application/x-www-form-urlencoded格式的表单数据
app.use(express.urlencoded({ extended: false }))
// app.use(express.json())

const joi = require('joi')

//解析token中间件
const { expressjwt: jwt } = require('express-jwt')
const config = require('./config')


//响应数据中间件
app.use((req, res, next) => {
  //默认值为1，表示失败的情况，0表示成功
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

app.use(jwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\/login/] }))

//导入路由模块并注册路由全局中间件
const userRouter = require('./router/user')
app.use('/api', userRouter)
const userinfoRouter = require('./router/userinfo')
app.use('/my', userinfoRouter)
const courseRouter = require('./router/course')
app.use('/course', courseRouter)
const tcRouter = require('./router/teachcourse')
app.use('/tc', tcRouter)
const chooseRouter = require('./router/choose')
app.use('/choose', chooseRouter)
const scoreRouter = require('./router/score')
app.use('/score', scoreRouter)

//定义错误级别中间件
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) {
    return res.cc(err)
  }
  if (err.name === 'UnauthorizedError') {
    return res.cc('身份认证失败！', 401)
  }
  res.cc(err)
})


//启动服务器
app.listen(80, () => {
  console.log('api server running at http://127.0.0.1:80')
})